package com.fvideo.framework.security.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.fvideo.common.core.domain.model.LoginUser;
import com.fvideo.common.utils.SecurityUtils;
import com.fvideo.common.utils.StringUtils;
import com.fvideo.framework.web.service.TokenService;

/**
 * token过滤器 验证token有效性
 * 
 * @author fvideo
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        // 1. 从请求中获取登录用户信息（通过tokenService解析JWT）
        LoginUser loginUser = tokenService.getLoginUser(request);

        // 当用户信息存在且当前未认证时
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
            // 2. 验证token有效性（过期/刷新等逻辑）
            tokenService.verifyToken(loginUser);

            // 3. 创建认证令牌，包含用户信息和权限
            // 参数说明：
            // 1. principal - 用户身份 (这里是 loginUser)
            // 2. credentials - 凭证（如密码，JWT场景下已通过验证故设为null）
            // 3. authorities - 权限列表
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                loginUser, null, loginUser.getAuthorities()); // 第三个参数是权限列表

            // 4. 设置请求详细信息（IP、Session等）
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

            // 5. 将认证信息存入Security上下文，完成鉴权
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }
}

